package com.podmanager.UI;

import java.io.File;

import com.podmanager.audio.*;
import com.podmanager.audio.MusicService.State;
import com.podmanager.data.DBContentProvider;
import com.podmanager.data.PMDatabase;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

public class PlayFragment extends Fragment implements  
								SeekBar.OnSeekBarChangeListener, Runnable, StateChangeListener {

	private Button play_prev_button, play_rewind_button, play_playpause_button, play_ffwd_button, play_next_button;
	private static SeekBar seekbar=null;
	
	public static final String ARG_SECTION_NUMBER = "section_number";
	private MusicService ms=null;
	private boolean seekbarIsChanging=false;
	private TextView play_episode_title;
	private TextView play_episode_description;
	private ImageView play_episode_image;
	private TextView play_episode_date;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 
 //       Bundle args = getArguments();
 
        View rootView = inflater.inflate(R.layout.play_layout, container, false);

        play_episode_title = (TextView) rootView.findViewById(R.id.play_episode_title);
        play_episode_image = (ImageView) rootView.findViewById(R.id.play_episode_image);
        play_episode_description = (TextView) rootView.findViewById(R.id.play_episode_description);
        play_episode_date = (TextView) rootView.findViewById(R.id.play_episode_date);
    	play_prev_button = (Button) rootView.findViewById(R.id.play_prev_button);
    	play_prev_button.setOnClickListener(this.play_prev_cl);
    	play_rewind_button = (Button) rootView.findViewById(R.id.play_rewind_button);
    	play_rewind_button.setOnClickListener(this.play_rewind_cl);
    	play_playpause_button = (Button) rootView.findViewById(R.id.play_playpause_button);
    	play_playpause_button.setOnClickListener(this.play_playpause_cl);
    	play_ffwd_button = (Button) rootView.findViewById(R.id.play_ffwd_button);
    	play_ffwd_button.setOnClickListener(this.play_ffwd_cl);
    	play_next_button = (Button) rootView.findViewById(R.id.play_next_button);
    	play_next_button.setOnClickListener(this.play_next_cl);
    	seekbar = (SeekBar) rootView.findViewById(R.id.play_seekbar);
    	seekbar.setOnSeekBarChangeListener(this);
		resetSeekBar();
		
		updateSeekBarPosition();
		displayFileData();
        return rootView;
    }
    private void ensureMediaService()
    {
    	if(ms==null)
    	{
    		ms=PodManager.getmMusicService();
    		if(ms!=null)
    		{
    			onStateChange(ms.setOnStateChangeListener(this));
    		}
    	}
    }

	private void resetSeekBar() {
		ensureMediaService();
		if(seekbar==null)return;
		seekbar.setMax(ms.getDuration());
		seekbar.setProgress(ms.getCurrentPosition());
	}
	private void performAction(String action, Bundle bundle) {
        MusicService.doStartMusicService(getActivity(), action, bundle);
		resetSeekBar();
	}

	public OnClickListener play_prev_cl = new OnClickListener() {
		@Override
		public void onClick(View v) {
	        performAction(MusicService.ACTION_PREV, null);
		}
	};
	public OnClickListener play_rewind_cl = new OnClickListener() {
		@Override
		public void onClick(View v) {
	        performAction(MusicService.ACTION_REWIND, null);
		}
	};
	public OnClickListener play_playpause_cl = new OnClickListener() {
		@Override
		public void onClick(View v) {
	        performAction(MusicService.ACTION_PLAYPAUSE, null);
		}
	};
	public OnClickListener play_ffwd_cl = new OnClickListener() {
		@Override
		public void onClick(View v) {
	        performAction(MusicService.ACTION_FFWD, null);
		}
	};
	public OnClickListener play_next_cl = new OnClickListener() {
		@Override
		public void onClick(View v) {
	        performAction(MusicService.ACTION_NEXT, null);
		}
	};
	private State musicServiceState;

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		this.seekbarIsChanging=true;
	}
	
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		Bundle bundle = new Bundle();
		bundle.putInt("POSITION", seekBar.getProgress());
		performAction(MusicService.ACTION_SET_POSITION, bundle);
		Log.d("move", seekBar.getProgress()+"/"+seekBar.getMax());
		this.seekbarIsChanging=false;
		if(this.musicServiceState==State.Started)
			updateSeekBarPosition();
	}

	private static Handler handler = new Handler();
	private void updateSeekBarPosition() {
	    if(this.musicServiceState!=State.Started)return;
	    handler.removeCallbacks(this);
	    if (this.ms == null)return; 
	    if(seekbarIsChanging)return;//don't update the position while seekbar is changing

		seekbar.setProgress(this.ms.getCurrentPosition());
		Log.d("handler", seekbar.getProgress()+"/"+seekbar.getMax());

    	handler.postDelayed(this, 500);
	}
	@Override
	public void run() {
		updateSeekBarPosition();
	}

	@Override
	public void onStateChange(State state) {
		musicServiceState = state;
		switch(state)
		{
		case Prepared:
			seekbar.setMax(ms.getDuration());
			seekbar.setProgress(ms.getCurrentPosition());
			displayFileData();
			break;
		case Started:
			updateSeekBarPosition();
			break;
		case Complete:
//			seekbar.setProgress(seekbar.getMax());
			break;
		}
	}
	private void displayFileData() {
		/*
		 * I know the code in here is poorly done, but working quickly to get all final features in place.
		 * would need to be refactored when more time is available.
		 */
		new GetFileData(this.getActivity())
		.execute(ms.getCurrentFile());
	}
	private Boolean validateFileAndSetBitmap(String file){
		if(!new File(file).exists())		return false;
        Bitmap b = BitmapFactory.decodeFile(file);
        if(b.getWidth()<5 ||b.getHeight()<5)return false;
        PlayFragment.this.play_episode_image.setImageBitmap(b);
        return true;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.ms.setOnStateChangeListener(null);
	}
	
	class GetFileData extends  AsyncTask<String, Void, String[]>{
		String [] columns = new String[]{PMDatabase.EPISODES.EPI_TITLE, 
										PMDatabase.EPISODES.EPI_IMAGE_PATH, 
										PMDatabase.EPISODES.EPI_DESCRIPTION, 
										PMDatabase.EPISODES.EPI_DATE, 
										PMDatabase.EPISODES.SUB_ROW_ID};
		private Context context;
		GetFileData(Context c){context=c;}
		@Override
		protected String[] doInBackground(String... params) {
			String selection= PMDatabase.EPISODES.FILE_PATH+"='"+params[0]+"'";
			Cursor c =context.getContentResolver().query(DBContentProvider.EPISODES_URI, columns, selection, null, null);
			if(c==null)return null;
			if(c.getCount()<1)return null;
			String[] returnValues=new String[columns.length		+1];
			c.moveToFirst();
			for(int i=0;i<columns.length;i++)
			{
				returnValues[i]=c.getString(c.getColumnIndex(columns[i]));
			}
			c.close();
			c=getActivity().getContentResolver().query(DBContentProvider.SUBSCRIPTION_URI,//URI 
										new String[]{PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_PATH},//columns/projection 
										PMDatabase.SUBSCRIPTIONS.KEY_ROW_ID+"="+returnValues[4], //selection
										null, null);//selectionArgs, sort
			if(c==null)return null;
			if(c.getCount()<1)return null;
			c.moveToFirst();
			returnValues[4]=c.getString(c.getColumnIndex(PMDatabase.SUBSCRIPTIONS.SUB_IMAGE_PATH));
			c.close();
			return returnValues;
		}
		@Override
		protected void onPostExecute(String[] result) {
			super.onPostExecute(result);
			if(result==null)return;
			PlayFragment.this.play_episode_title.setText(result[0]);
			PlayFragment.this.play_episode_description.setText(result[2]);
			PlayFragment.this.play_episode_date.setText(result[3]);
			if(validateFileAndSetBitmap(result[1]))return;//exit if episode image is properly set
			validateFileAndSetBitmap(result[4]);
			
		}
	}
}
